package com.zhao.demo.controller;

import com.alibaba.fastjson.JSON;
import com.zhao.demo.pojo.User;
import com.zhao.demo.service.UserService;
import jdk.nashorn.api.scripting.JSObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author xiaoZhao
 * @date 2022/7/24
 * @describe
 */
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    // 用户列表
    @GetMapping("/users")
    public String getUsers() {
        List<User> userList = userService.getUserList();
        String s = JSON.toJSONString(userList);
        return s;
    }

    // 单个用户
    @GetMapping("/user/{id}")
    public User getUserById(@PathVariable Integer id) {
        return userService.getUserById(id);
    }

    // 添加用户
    @GetMapping("/addUser")
    public void addUser(@RequestParam("id") Integer id,
                        @RequestParam("name") String name,
                        @RequestParam("age") Integer age,
                        @RequestParam("email") String email,
                        @RequestParam("phone") String phone) {

        User user = new User(id,name,age,email,phone);
        int result = userService.addUser(user);
        if (result > 0) {
            System.out.println("添加成功");
            getUserById(user.getId());
        } else {
            System.out.println("添加失败");
        }
    }

    // 删除用户
    @GetMapping("/delete/{id}")
    public void deleteUser(@PathVariable Integer id){
        int result = userService.deleteUser(id);
        if (result > 0) {
            System.out.println("删除成功");
        } else {
            System.out.println("删除失败");
        }
    }

    // 修改用户
    @GetMapping("/update")
    public void updateUser(@RequestParam("id") Integer id,
                           @RequestParam("name") String name,
                           @RequestParam("age") Integer age,
                           @RequestParam("email") String email,
                           @RequestParam("phone") String phone){
        User user = new User(id,name,age,email,phone);
        int result = userService.updateUser(user);
        if (result > 0) {
            System.out.println("更新成功");
        } else {
            System.out.println("更新失败");
        }
    }

}
